import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private DatagramSocket socket=null;
    public UdpEchoServer(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动...");
        while(true){
            DatagramPacket requestPacket=new DatagramPacket(new byte[4048],4048);
            //接受请求
            socket.receive(requestPacket);
            String request=new String(requestPacket.getData(),0,requestPacket.getLength());
            //根据请求计算响应
            String response=process(request);
            //返回响应
            DatagramPacket responsePacket=new DatagramPacket(response.getBytes(),response.getBytes().length,requestPacket.getSocketAddress());
            socket.send(responsePacket);
            //打印日志
            System.out.printf("[%s:%d]  req:%s   rep:%s\n",requestPacket.getAddress().toString(),requestPacket.getPort(),request,response);
        }
    }
    private String process(String s){
        //此处实现简单的回显服务器，工作根据实际情况添加逻辑代码
        return s;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server=new UdpEchoServer(8776);
        server.start();
    }
}
